<?php

namespace App\Http\Controllers\Api\V1\Game;

use App\Models\Conf\Site;
use App\Models\Inf\Player;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use App\Models\Def\MainGamePlat;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;


class EbetController extends Controller
{
    use Helpers;

    public function login(Request $request)
    {
        $params = json_decode($request->getContent(), true);
        if (is_array($params)) {
            if (array_key_exists('accessToken', $params)) {
                $token = str_replace('-', '=', $params['accessToken']);
                $username = $params['username'];
                if (Cache::get($params['username']) == $token) {
                    $data = json_decode(decrypt($token), true);

                    if (is_array($data)) {
                        if (array_key_exists('site_username', $data)) {
                            $site = Site::where('username', $data['site_username'])->first();
                            $plat = MainGamePlat::where('main_game_plat_code', $data['plat'])->first();
                            $player = Player::where([
                                    ['site_id', '=', $site->id],
                                    ['username', '=', $data['username']],
                                    ['password', '=', $data['password']],
                                    ['main_game_plats_id', '=', $plat->id],
                                ]
                            )->first();
                            if ($player) {
                                return $this->ebResponse('200', $token, $username);
                            } else {
                                return $this->ebResponse('401', $token, $username);
                            }
                        }
                        return $this->ebResponse('4026', $token, $username);
                    }
                } else {
                    return $this->ebResponse('410', $token, $username);
                }
            }
        } else {
            return $this->response->array([
                    'status' => 500,
                    'message' => '未携带token参数',
                ]
            );
        }

    }


    /**
     * gameapi
     * 2018/12/3 20:12
     * Administrator
     * response
     *
     * @param $status
     * @param $token
     * @param $username
     * @return mixed
     */
    private function ebResponse($status, $token, $username)
    {
        Cache::forget($username);
        return $this->response->array([
                'status' => $status,
                'subchannelId' => 0,
                'accessToken' => $token,
                'username' => $username,
                'nickname' => $username,
            ]
        );
    }
}
